<?php
class Habit extends MY_Controller{

	public function get_by_id()
	{
		$data = $this->user_post_data;
    	if(!empty($data)){
    		$this->load->model("Habits");
            $task_info = $this->Habits->get_habit_info($data['habit_id']);

            $week_result = $this->Habits->get_week_habit_list($data['habit_id']);
           	// echo $week_start_time = strtotime(date('Y-m-d', time())) - date('w',strtotime(date('Y-m-d', time())))*86400 + 3600 * 24;
            $first=1;  
            $sdefaultDate = date("Y-m-d");  
            $w=date('w',strtotime($sdefaultDate));  
            //获取本周开始日期，如果$w是0，则表示周日，减去 6 天  
            $week_start_time=strtotime(date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'))); 
            $week_data = array();
            for($i = 0; $i < 7; $i++){
                $week_data[$i]['today_start_time'] = $week_start_time + 3600 * 24 * $i;
                $week_data[$i]['today_end_time'] = $week_start_time + 3600 * 24 * ($i+1);
                $week_data[$i]['date'] = date("Y-m-d", $week_data[$i]['today_start_time']);
            }
            // print_r($week_result);
            $weeks = array("一", "二", "三", "四", "五", "六", "日");
            if(count($week_result)){
                foreach ($week_result as $key => $value) {
                    foreach ($week_data as $k => $v) {
                        if(empty($v['record_id'])){
                            if($value['time'] >= $v['today_start_time'] && $value['time'] < $v['today_end_time']){
                                $value['date'] = $v['date'];
                                $week_data[$k]['record_id'] = $value['id'];
                                $week_data[$k]['stars'] = $value['stars'];
                            }else{
                                $week_data[$k]['record_id'] = 0;
                                $week_data[$k]['stars'] = 0;
                            }
                            $week_data[$k]['week'] = $weeks[$k];
                        }
                    }
                }
            }else{
                foreach ($week_data as $k => $v) {
                    $week_data[$k]['week'] = $weeks[$k];
                    $week_data[$k]['record_id'] = 0;
                    $week_data[$k]['stars'] = 0;
                }
            }
            $week = date('N', time());
            $task_info['today_week'] = $weeks[$week-1];

            $statistics_info = array("max_continuity" => 0, "total_stars" => 0, "continuity" => 0, "continuity_type" => 0);
            $statistics = get_field_by_where("user_children_task_type_statistics", "*", "task_id='{$data['habit_id']}'");
            if($statistics){
                $statistics_info['total_stars'] = $statistics['total_stars'];
                $statistics_info['continuity'] = $statistics['continuity'];
            }
            $max_continuity = get_field_by_where("user_children_max_continuity_record", "continuity,end_time", "task_id='{$data['habit_id']}' AND child_id = '{$data['child_id']}' ORDER BY continuity DESC");
            if($max_continuity){
                $statistics_info['max_continuity'] = $max_continuity['continuity'];
            }

            $last_continuity = get_field_by_where("user_children_max_continuity_record", "end_time", "task_id='{$data['habit_id']}' AND child_id = '{$data['child_id']}' ORDER BY id DESC");
            $today_time = strtotime(date("Y-m-d", time()));
            $yesterday_time = $today_time - 3600 * 24;
            if($last_continuity){
                if($last_continuity['end_time'] < $yesterday_time){
                    $statistics_info['continuity'] = 0; //已连续0
                }
            }else{
                $statistics_info['continuity'] = 0; //已连续0
            }

            $recommend_list = $this->Habits->get_recommend_list($task_info['task_type_id']);

            $conditions['type'] = 1;
            $conditions['category_id'] = $task_info['task_type_id'];
            if(!empty($data['child_id'])){
                $conditions['child_id'] = $data['child_id'];
            }
            $this->load->model("Users");
            $user_dynamic = $this->Users->get_child_dynamics(0, $this->offset, $conditions);
            $user_dynamic['total_page'] = ceil($user_dynamic['count'] / $this->offset);
            foreach ($user_dynamic['list'] as $key => $value) {
                $text = "坚持 #{$value['name']}# " . "第{$value['day']}天<br>";
                $user_dynamic['list'][$key]['text'] = $text . $user_dynamic['list'][$key]['text'];
            }
            echo json_encode(array("code" => 1, "data" => $task_info, "record" => $week_data, "statistics_info" => $statistics_info, "recommend_list" => $recommend_list, "user_dynamic" => $user_dynamic));   // 
    	}else{
            echo json_encode(array("code" => 404, "data" => 'not data'));
        }
	}

    function get_user_habti_dynamic(){
        $data = $this->user_post_data;
        $this->load->model("Habits");
        $this->load->model("Users");
        $task_info = $this->Habits->get_habit_info($data['habit_id']);
        $conditions['type'] = 1;
        $conditions['category_id'] = $task_info['task_type_id'];
        if(!empty($data['child_id'])){
            $conditions['child_id'] = $data['child_id'];
        }
        $limit = !empty($data['limit']) ? $data['limit'] * $this->offset : 0;
        $user_dynamic = $this->Users->get_child_dynamics($limit, $this->offset, $conditions);
        echo json_encode(array("code" => 1, "data" => $user_dynamic));
    }

    //发布动态
    function dynamic(){
        $data = $this->user_post_data;
        $task_record_info = get_field_by_where("task_records", "id,task_id", "child_id='{$data['user_token']['child_id']}' AND task_id='{$data['habit_id']}'");
        if(!empty($task_record_info['id'])){
            $image = !empty($data['image']) ? get_qiniu_url($data['image']) : "";
            $this->db->update("task_records", array("text" => $data['text'], "image" => $image), array("id" => $task_record_info['id']));
            if($this->db->affected_rows() > 0){
                $habit_type = get_field_by_where("tasks", "task_type_id", "id='{$data['habit_id']}'");
                $today_time = strtotime(date("Y-m-d", time()));
                $user_dynamic_info = get_field_by_where("user_dynamics", "id", "child_id='{$data['user_token']['child_id']}' AND type = 1 AND data_id='{$data['habit_id']}' AND add_time >= '{$today_time}'");
                $user_dynamic_data['user_id']       = $data['user_token']['user_id'];
                $user_dynamic_data['child_id']      = $data['user_token']['child_id'];
                $user_dynamic_data['type']          = 1;
                $user_dynamic_data['data_id']       = $data['habit_id'];
                $user_dynamic_data['category_id']   = $habit_type['task_type_id'];
                $user_dynamic_data['stars']         = 1;
                $user_dynamic_data['text']          = $data['text'];
                $user_dynamic_data['image']         = $image;
                $user_dynamic_data['add_time']      = time();
                if(!empty($user_dynamic_info['id'])){
                    //更新动态数据
                    $this->db->update("user_dynamics", $user_dynamic_data, array("id" => $user_dynamic_info['id']));
                }else{
                    //写入动态数据
                    $dynamic_total = get_field_by_where("user_dynamics", "count(id) AS count", "child_id='{$data['user_token']['child_id']}' AND type = 1 AND data_id='{$data['habit_id']}'");
                    $user_dynamic_data['day'] = !empty($dynamic_total['count']) ? $dynamic_total['count'] + 1: 1;
                    $this->db->insert("user_dynamics", $user_dynamic_data);
                }
            }
            echo json_encode(array("code" => 1));
        }
    }

    function get_dynamic(){
        $data = $this->user_post_data;
        $user_dynamic_info = get_field_by_where("user_dynamics", "*", "child_id='{$data['user_token']['child_id']}' AND type = 1 AND data_id='{$data['habit_id']}'");
        echo json_encode(array("code" => 1, "data" => $user_dynamic_info));
    }

    function get_today_habit(){
        $data = $this->user_post_data;
        $this->load->model("Tasks");
        if(empty($data['user_token']['child_id'])){
            echo json_encode(array("code" => 0, "msg" => "缺少孩子ID"));exit;
        }
        $pid = !empty($data['pid']) ? $data['pid'] : 0;
        $week = date('N', time());
        $task_list = $this->Tasks->get_task_list(0,0,array("pid" => $pid, "child_id"=>$data['user_token']['child_id'], "find_ini_set" => $week));
        $task_list_data = array('count' => 0, 'list' => array());
        if(!empty($task_list['count'])){
            $task_list_data['count'] = $task_list['count'];
            foreach ($task_list['list'] as $key => $value) {
                $value['total_stars'] = $value['continuity'] = 0;
                $statistics = get_field_by_where("user_children_task_type_statistics", "*", "task_id='{$value['id']}'");
                if($statistics){
                    $value['continuity'] = $statistics['continuity'];
                    $value['total_stars'] = $statistics['total_stars'];
                }
                /*$last_continuity = get_field_by_where("user_children_max_continuity_record", "continuity,end_time", "task_id='{$value['id']}' AND child_id = '{$data['user_token']['child_id']}' ORDER BY id DESC");
                $today_time = strtotime(date("Y-m-d", time()));
                $yesterday_time = $today_time - 3600 * 24;
                if($last_continuity){
                    if($last_continuity['end_time'] >= $yesterday_time && $last_continuity['end_time'] < $today_time){
                        $statistics_info['continuity'] = $statistics_info['continuity'];
                    }elseif($last_continuity['end_time'] < $today_time){
                        $statistics_info['continuity'] = 0;
                    }
                }
                $value['continuity'] = $statistics_info['continuity'];*/
                if(!empty($value['task_time'])){
                    $task_list_data['time_line'][] = $value;
                }else{
                    $task_list_data['list'][] = $value;
                }
            }
        }
        echo json_encode(array("code" => 1, "data" => $task_list_data));
    }

    function join(){
        $data = $this->user_post_data;
        if($data['reward'] == 1){
            if($data['start_time'] == '开始时间'){
                echo json_encode(array("code" => 0, "msg" => "请选择开始时间"));
                exit;
            }
            if($data['end_time'] == '结束时间'){
                echo json_encode(array("code" => 0, "msg" => "请选择结束时间"));
                exit;
            }
            $start_time = strtotime($data['start_time']);
            $end_time = strtotime($data['end_time']);
            if($start_time >= $end_time){
                echo json_encode(array("code" => 0, "msg" => "激励设置的结束时间必须大于开始时间"));
                exit;
            }
            $days = ($end_time - $start_time) / 86400;
        }
        if(empty($data['task_type_id'])){
            //没有task_type_id为自定义习惯
            $task_type_info = get_field_by_where("task_types", "*", "name='{$data['task_type_name']}'");
            if(!empty($task_type_info['id'])){
                $data['task_type_id'] = $task_type_info['id'];
            }else{
                $task_types_data['pid'] = '-1';
                $task_types_data['user_id'] = $data['user_token']['user_id'];
                $task_types_data['name'] = $data['task_type_name'];
                $task_types_data['image'] = 'http://img.zhaorenxue.com/FqtjHpSbl7VHStbyAMAXqFtY54rk';
                $task_types_data['type'] = 0;
                $task_types_data['default_time'] = $data['task_time'];
                $task_types_data['remark'] = !empty($data['describe']) ? $data['describe'] : NULL;
                $task_types_data['repeat'] = !empty($data['repeat']) ? $data['repeat'] : '1,2,3,4,5,6,7';
                $task_types_data['status'] = 0;
                $task_types_data['add_time'] = time();
                $this->db->insert("task_types", $task_types_data);
                $data['task_type_id'] = $this->db->insert_id();
            }
        }
        $task_data['user_id'] = $data['user_token']['user_id'];
        $task_data['child_id'] = !empty($data['user_token']['child_id']) ? $data['user_token']['child_id'] : 0;
        $task_data['name'] = $data['task_type_name'];
        $task_data['task_type_id'] = $data['task_type_id'];
        // $task_data['stars'] = !empty($data['stars']) ? $data['stars'] : 0;
        $task_data['repeat'] = !empty($data['repeat']) ? $data['repeat'] : '1,2,3,4,5,6,7';
        $task_data['describe'] = !empty($data['describe']) ? $data['describe'] : NULL;
        $task_data['add_time'] = time();
        if(!empty($data['task_time'])){
            $task_data['task_time'] = $data['task_time'];
            $task_time = explode(":", $data['task_time']);
            $task_data['remind_hour'] = $task_time[0];
            $task_data['remind_min'] = $task_time[1];
        }
        $this->db->insert("tasks", $task_data);
        $insert_id = $this->db->insert_id();
        $habit_reward_id = 0;
        if($insert_id > 0){
            $this->db->where("id", $data['task_type_id']);
            $this->db->set("use_number", "use_number+1", false);
            $this->db->update("task_types");
            if($data['reward'] == 1){
                //写入激励数据
                $habit_reward_data['user_id'] = $data['user_token']['user_id'];
                $habit_reward_data['child_id'] = $data['user_token']['child_id'];
                $habit_reward_data['task_id'] = $insert_id;
                $habit_reward_data['days'] = $days;
                $habit_reward_data['reward'] = $data['reward_text'];
                $habit_reward_data['add_time'] = time();
                $this->db->insert("habit_reward", $habit_reward_data);
                $habit_reward_id = $this->db->insert_id();
            }
        }

        echo json_encode(array("code" => 1, "data" => array("id" => $insert_id, "habit_reward_id" => $habit_reward_id)));
    }

    function get_habit_info(){
        $data = $this->user_post_data;
        $this->load->model("Habits");
        $user_habit_info = get_field_by_where("tasks", "id", "task_type_id='{$data['habit_type_id']}' AND child_id='{$data['child_id']}'");
        $user_habit_id = !empty($user_habit_info['id']) ? $user_habit_info['id'] : 0;
        $recommend_list = $this->Habits->get_recommend_list($data['habit_type_id']);
        $conditions['type'] = 1;
        $conditions['category_id'] = $data['habit_type_id'];
        $this->load->model("Users");
        $limit = !empty($data['limit']) ? $data['limit'] * $this->offset : 0;
        $user_dynamic = $this->Users->get_child_dynamics($limit, $this->offset, $conditions);
        if($user_dynamic['count'] > 0){
            foreach ($user_dynamic['list'] as $key => $value) {
                if(empty($value['head_img_url'])){
                    if($value['gender'] == 1){
                        $user_dynamic['list'][$key]['head_img_url'] = get_qiniu_url('FtE8Gn7PqWv0W7aVTuab8RcuGxlm');
                    }else{
                        $user_dynamic['list'][$key]['head_img_url'] = get_qiniu_url('Fsof6z54HyIM401i0amzqo3VzrF3');
                    }
                }
                $text = "坚持 #{$value['name']}# " . "第{$value['day']}天<br>";
                $user_dynamic['list'][$key]['text'] = $text . $user_dynamic['list'][$key]['text'];
            }
        }
        $user_dynamic['total_page'] = ceil($user_dynamic['count'] / $this->offset);
        echo json_encode(array("code" => 1, "data" => array( "recommend_list" => $recommend_list, "user_dynamic" => $user_dynamic, "user_habit_id" => $user_habit_id)));
    }

    function hot_list(){
        $this->load->model("Habits");
        $hot_list = $this->Habits->get_hot_habit_list();
        echo json_encode(array("code" => 1, "data" => $hot_list));
    }

    function get_habti_user_dynamic(){
        $data = $this->user_post_data;
        $this->load->model("Users");
        $conditions['type'] = 1;
        $conditions['category_id'] = $data['task_type_id'];
        if(!empty($data['child_id'])){
            $conditions['child_id'] = $data['child_id'];
        }
        $limit = !empty($data['limit']) ? $data['limit'] * $this->offset : 0;
        $user_dynamic = $this->Users->get_child_dynamics($limit, $this->offset, $conditions);
        echo json_encode(array("code" => 1, "data" => $user_dynamic));
    }

    function reward_detial(){
        $data = $this->user_post_data;
        $reward_info = get_field_by_where("habit_reward", "*", "id='{$data['reward_id']}'");
        if($reward_info){
            echo json_encode(array("code" => 1, "data" => $reward_info));
        }else{
            echo json_encode(array("code" => 0, "msg" => "该奖励不存在"));
        }
    }

    function get_reward(){
        $data = $this->user_post_data;
        $reward_info = get_field_by_where("habit_reward", "id,get_status", "id='{$data['reward_id']}'");
        if($reward_info){
            if($reward_info['get_status'] == 1){
                echo json_encode(array("code" => 0, "msg" => "该奖品已经领取过了。"));
                exit;
            }
            $this->db->update("habit_reward", array("get_status" => 1, "get_time" => time()), array("id" => $data['reward_id']));
            if($this->db->affected_rows() > 0){
                echo json_encode(array("code" => 1));
            }else{
                echo json_encode(array("code" => 0, "msg" => "操作失败,请稍后重试。"));
            }
        }else{
            echo json_encode(array("code" => 0, "msg" => "该奖励不存在"));
        }
    }
}